//
//  SHLiveManager.m
//  Netease
//
//  Created by 王方伟 on 2017/8/23.
//  Copyright © 2017年 wfw. All rights reserved.
//

#import "NTESLiveManager.h"
#import "NSDictionary+Extension.h"
#import "NTESPresentAttachment.h"
#import "NTESPresent.h"

@interface NTESLiveManager ()<NIMChatManagerDelegate>
@property (strong, nonatomic) NSMutableDictionary *myInfo;
@property (strong, nonatomic) NSMutableDictionary *chatrooms;
//连麦队列
@property (strong, nonatomic) NSMutableArray<NTESMicConnector *> *connectors;
//收到的礼物信息
@property (nonatomic,strong) NSMutableArray<NTESPresentItem *> *presentBox;
@property (strong, nonatomic) NSMutableDictionary *anchorInfo;
@property (copy, nonatomic) NSString *presentBoxDataPath;
@end

@implementation NTESLiveManager

+ (instancetype)sharedLiveManager{
    static NTESLiveManager *sharedClasse;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClasse = [[NTESLiveManager alloc] init];
    });
    return sharedClasse;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _anchorInfo = [[NSMutableDictionary alloc] init];
        _chatrooms = [[NSMutableDictionary alloc] init];
        _connectors = [[NSMutableArray alloc] init];
        _myInfo = [[NSMutableDictionary alloc] init];
        [self unarchivePresentBox];
        [[NIMSDK sharedSDK].chatManager addDelegate:self];
    }
    return self;
}


- (void)unarchivePresentBox{
    NSString *filepath = self.presentBoxDataPath;
    NSArray *array= @[];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        id object = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
        array = [object isKindOfClass:[NSArray class]] ? object : @[];
    }
    self.presentBox = [array mutableCopy];
}

- (void)setOrientation:(NIMVideoOrientation)orientation{
    _orientation = orientation;
}


- (void)cacheMyInfo:(NIMChatroomMember *)info roomId:(NSString *)roomId{
    [_myInfo setObject:info forKey:roomId];
}

- (void)cacheChatroom:(NIMChatroom *)chatroom{
    [_chatrooms setObject:chatroom forKey:chatroom.roomId];
}

#pragma mark 我在聊天室内的信息
- (NIMChatroomMember *)myInfo:(NSString *)roomId{
    NIMChatroomMember *member = _myInfo[roomId];
    return member;
}

#pragma mark 更新连麦者
- (void)updateConnectors:(NTESMicConnector *)connector{
    NTESMicConnector *localCon = [self findConnector:connector.uid];
    if (!localCon){
        [self.connectors addObject:connector];
    }else{
        localCon.state = connector.state;
    }
}

#pragma mark 移除连麦者
- (void)removeConnectors:(NSString *)uid{
    NTESMicConnector *connector = [self findConnector:uid];
    if (connector) {
        [self.connectors removeObject:connector];
    }
}

#pragma mark 移除所有连麦者
- (void)removeAllConnectors{
    [self.connectors removeAllObjects];
}


- (NTESMicConnector *)findConnector:(NSString *)uid{
    for (NTESMicConnector *connector in self.connectors) {
        if ([connector.uid isEqualToString:uid]) {
            return connector;
        }
    }
    return nil;
}

- (void)setConnectorOnMic:(NTESMicConnector *)connectorOnMic{
    if (![_connectorOnMic.uid isEqualToString:connectorOnMic.uid]) {
        SHLog(@"connector on mic changed %@ -> %@",_connectorOnMic.uid,connectorOnMic.uid);
    }
    _connectorOnMic = connectorOnMic;
}


- (NSArray<NTESMicConnector *> *)connectors:(NTESLiveMicState)state{
    NSMutableArray *result = [[NSMutableArray alloc] init];
    for (NTESMicConnector *connector in self.connectors) {
        if (connector.state == state) {
            [result addObject:connector];
        }
    }
    return [NSArray arrayWithArray:result];
}

- (void)anchorInfo:(NSString *)roomId handler:(void(^)(NSError *,NIMChatroomMember *))handler{
    if (!handler) {
        return;
    }
    NIMChatroomMember *member = _anchorInfo[roomId];
    if (member) {
        handler(nil,member);
        return;
    }
    NIMChatroom *chatroom = self.chatrooms[roomId];
    if (chatroom) {
        NIMChatroomMembersByIdsRequest *requst = [[NIMChatroomMembersByIdsRequest alloc] init];
        requst.roomId = roomId;
        requst.userIds = @[chatroom.creator];
        [[NIMSDK sharedSDK].chatroomManager fetchChatroomMembersByIds:requst completion:^(NSError *error, NSArray *members) {
            handler(error,members.firstObject);
        }];
    }
}

- (NSDictionary *)presents{
    static NSMutableDictionary *presents;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        presents = [[NSMutableDictionary alloc] init];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Presents" ofType:@"plist"];
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
        for (NSString *key in dict) {
            NSDictionary *p = dict[key];
            NTESPresent *present = [[NTESPresent alloc] init];
            present.type = key.integerValue;
            present.name = p[@"name"];
            present.icon = p[@"icon"];
            [presents setObject:present forKey:key];
        }
    });
    return presents;
}

- (NIMChatroom *)roomInfo:(NSString *)roomId{
    return _chatrooms[roomId];
}

- (NSArray<NTESPresentItem *> *)myPresentBox{
    return self.presentBox;
}

#pragma mark - NIMChatManagerDelegate
- (void)onRecvMessages:(NSArray *)messages{
    for (NIMMessage *message in messages) {
        NSString *room = message.session.sessionId;
        NIMChatroomMember *member = [self myInfo:room];
        NIMCustomObject *object = message.messageObject;
        if (member.type == NIMChatroomMemberTypeCreator && [object isKindOfClass:[NIMCustomObject class]] && [object.attachment isKindOfClass:[NTESPresentAttachment class]]) {
            NTESPresentAttachment *attach = object.attachment;
            [self savePresent:attach.presentType count:attach.count];
        }
    }
}

- (void)savePresent:(NSInteger)presentType count:(NSInteger)count{
    NTESPresentItem *presentItem;
    for (NTESPresentItem *item in self.presentBox) {
        if (item.type == presentType) {
            presentItem = item;
            break;
        }
    }if (!presentItem) {
        presentItem = [[NTESPresentItem alloc] init];
        presentItem.type  = presentType;
        [self.presentBox addObject:presentItem];
    }
    presentItem.count++;
}


- (void)stop{
   
}
@end
